package com.tocea.formation.users;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;


import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.thoughtworks.xstream.XStream;
import com.tocea.formation.books.BookImpl;

public class UserDAO {

	private List<IUser> users;
	private XStream stream = new XStream();
	private String FILE_PATH = "users.xml";
	
	public UserDAO(List<IUser> utilisateurs) throws IOException{
		this.users = utilisateurs;
		stream.alias("Users", IUser.class);
		stream.useAttributeFor("id", Integer.class);
	}
	
	public void save() throws IOException{
		PrintWriter w = new PrintWriter(FILE_PATH);
		String xml = stream.toXML(users);
		w.write(xml);
		w.flush();
		w.close();
		
	}
	public UserImpl get(Integer id){
		
		org.jdom.Document document = null ;
        SAXBuilder sxb = new SAXBuilder();
        
        try {
			document = sxb.build(FILE_PATH);
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
        
        Element racine = document.getRootElement();
        XPath xpa;
		try {
			xpa = XPath.newInstance("//[@id='"+id+"']");
	        List results = xpa.selectNodes(racine);
	        if(results.size()==0)return null;
	        Element noeudCourant = (Element) results.get(0);
	        String author, name, pwd;
	        
	        
	        xpa = XPath.newInstance("./name");
	        name= xpa.valueOf(noeudCourant);
	        xpa = XPath.newInstance("./pwd");
	        pwd= xpa.valueOf(noeudCourant);
	        
	        
	        return new UserImpl(name, id, pwd);
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}   
		return null;


		

	}
}
